<template>
  <div id="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryinfo.query" placeholder="请输入内容" @blur="getUserList" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click.stop="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="openAddUserDialog">新增用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userlist" border stripe style="width: 100%">
        <el-table-column type="index" width="50" fixed> </el-table-column>
        <el-table-column prop="username" label="用户名" width="200" fixed> </el-table-column>
        <el-table-column prop="tel" label="电话" width="200"> </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"> </el-table-column>
        <el-table-column prop="createtime" label="创建时间" width="280" sortable> </el-table-column>
        <el-table-column prop="role" label="角色" width="180"> </el-table-column>
        <el-table-column label="状态" width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mgstate" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="openEditDialog(scope.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUser(scope.row)"></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="edit1(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryinfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryinfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>
    <el-dialog title="新增用户" width="40%" :visible.sync="addUserVisible" @close="closeAddUserDialog">
      <el-form :model="addUserForm" :rules="addUserFormRule" ref="addUserFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input v-model="addUserForm.pwd"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="tel">
          <el-input v-model="addUserForm.tel"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser('addUserFormRef')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改用户" width="40%" :visible.sync="editUserVisible" @close="closeEditUserDialog">
      <el-form :model="editUserForm" :rules="editUserFormRule" ref="editUserFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="tel">
          <el-input v-model="editUserForm.tel"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser('editUserFormRef')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs'
export default {
  name: 'users',
  data() {
    var checkTel = (addUserFormRule, value, callback) => {
      const regTel = /^1[3|4|5|8][0-9]\d{4,8}$/
      if (regTel.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号码'))
    }
    var checkEmail = (addUserFormRule, value, callback) => {
      const regEmail = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    return {
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userlist: [],
      total: 0,
      addUserVisible: false,
      editUserVisible: false,
      addUserForm: {
        username: '',
        pwd: '',
        tel: '',
        email: ''
      },
      editUserForm: {
        id: '',
        username: '',
        tel: '',
        email: ''
      },
      addUserFormRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkTel, trigger: 'blur' }
        ]
      },
      editUserFormRule: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkTel, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this._getUserList()
  },
  methods: {
    // 获取用户列表
    async _getUserList() {
      const { data: res } = await this.$http.get('/getPageUsers', { params: this.queryinfo })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: res.meta.msg,
          type: 'error'
        })
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 分页页数改变事件
    handleSizeChange(newsize) {
      this.queryinfo.pagesize = newsize
      this.queryinfo.pagenum = 1
      this._getUserList()
    },
    // 分页页码改变事件
    handleCurrentChange(newnum) {
      this.queryinfo.pagenum = newnum
      this._getUserList()
    },
    // 获取用户列表事件
    getUserList() {
      this.queryinfo.pagenum = 1
      this._getUserList()
    },
    // 修改用户状态
    async changeState(row) {
      const { data: res } = await this.$http.get('/changeUserState', {
        params: {
          userid: row.id,
          state: row.mgstate === true ? 1 : 0
        }
      })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: res.meta.msg,
          type: 'error'
        })
      } else {
        this.$message({
          message: res.meta.msg,
          type: 'success'
        })
      }
    },
    // 打开新增用户对话框
    openAddUserDialog() {
      this.addUserVisible = true
    },
    // 打开修改用户对话框
    async openEditDialog(row) {
      this.editUserVisible = true
      const { data: res } = await this.$http.get('/getUserByID?id=' + row.id)
      this.editUserForm.id = res.data.id
      this.editUserForm.username = res.data.username
      this.editUserForm.tel = res.data.tel
      this.editUserForm.email = res.data.email
    },
    // 新增用户
    addUser(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http({
          url: '/addUser',
          method: 'post',
          transformRequest: [
            function(data) {
              // 对 data 进行任意转换处理
              return qs.stringify(data)
            }
          ],
          data: this.addUserForm
        })
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'error'
          })
        } else {
          this.$message({
            message: res.meta.msg,
            type: 'success'
          })
          this.addUserVisible = false
          this._getUserList()
        }
      })
    },
    // 修改用户
    editUser(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http('/editUser', { params: this.editUserForm })
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'error'
          })
        } else {
          this.$message({
            message: res.meta.msg,
            type: 'success'
          })
          this.editUserVisible = false
          this._getUserList()
        }
      })
    },
    deleteUser(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.get('/delUser?id=' + row.id)
          if (res.meta.status !== 200) {
            this.$message({
              type: 'error',
              message: res.meta.msg
            })
          }
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
          this._getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 监听关闭新增用户对话框
    closeAddUserDialog() {
      this.$refs.addUserFormRef.resetFields()
    },
    // 监听关闭修改用户对话框
    closeEditUserDialog() {
      this.$refs.editUserFormRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped></style>
